package com.sservice.service.service.impl;

import com.sservice.common.Constants;
import com.sservice.model.dao.AdvanceReceiptMapper;
import com.sservice.model.entity.AdvanceReceipt;
import com.sservice.model.entity.ClienteleAccount;
import com.sservice.model.vo.AdvanceReceiptVo;
import com.sservice.service.service.IAdvanceReceiptService;
import com.sservice.service.service.IClienteleAccountService;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by suweiming on 2017/12/20.
 */

@Service
public class AdvanceReceiptServiceImpl implements IAdvanceReceiptService {


    @Autowired
    private AdvanceReceiptMapper dao;
    @Autowired
    private IClienteleAccountService clienteleAccountService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(AdvanceReceipt record) {
        return dao.insert(record);
    }

    @Override
    public int insertSelective(AdvanceReceipt record) {
        if (record.getNo() == null) {
            if ("1".equals(record.getType())) {
                AdvanceReceipt ar = new AdvanceReceipt();
                ar.setNo("YSK");
                record.setNo(Constants.generateServiceNO("YSK", Constants.generateLimitNumberStr(getMaxInNoOrder(ar) + 1, 4)));
            } else if ("2".equals(record.getType())) {
                AdvanceReceipt ar = new AdvanceReceipt();
                ar.setNo("YFK");
                record.setNo(Constants.generateServiceNO("YFK", Constants.generateLimitNumberStr(getMaxInNoOrder(ar) + 1, 4)));
            }

        }
        return dao.insertSelective(record);
    }

    /**
     * @param record
     * @return
     */
    @Transactional
    @Override
    public Object createAdvanceReceipt(AdvanceReceipt record) {
        if (record.getNo() == null) {
            AdvanceReceipt ar = new AdvanceReceipt();
            ar.setNo("YSK");
            record.setNo(Constants.generateServiceNO("YSK", Constants.generateLimitNumberStr(getMaxInNoOrder(ar) + 1, 4)));
        }
        record.setType("0");
        ClienteleAccount ca = clienteleAccountService.selectClientAccountByClientele(record.getClienteleId());
        Boolean flag = false;
        if (ca == null) {
            flag = true;
            ca = new ClienteleAccount();
            ca.setClienteleId(record.getClienteleId());
            ca.setYushouRemain(BigDecimal.valueOf(0.0));
            ca.setYushouTotal(BigDecimal.valueOf(0.0));
        }
        ca.setYushouRemain((record.getTotalDeposit().add(ca.getYushouRemain())));
        ca.setYushouTotal(record.getTotalDeposit().add(ca.getYushouTotal()));
        accountDesc(flag, ca);
        int res = dao.insertSelective(record);
        if (res > 0) {
            return res;
        }
        throw new Error("保存预收款失败!");
    }

    @Transactional
    @Override
    public Object delete(AdvanceReceipt record) {
        AdvanceReceipt ar = dao.selectByPrimaryKey(record.getId());
        if (ar.getTotalVerified().compareTo(BigDecimal.valueOf(0.0)) == 1) {
            return "预收款单已全部或部分核销，不能删除！";
        }
        ClienteleAccount ca = clienteleAccountService.selectClientAccountByClientele(ar.getClienteleId());
        Boolean flag = false;
        ca.setYushouRemain(ca.getYushouRemain().subtract(ar.getTotalDeposit()));
        ca.setYushouTotal(ca.getYushouTotal().subtract(ar.getTotalDeposit()));
        accountDesc(flag, ca);
        int res = dao.deleteByPrimaryKey(record.getId());
        if (res > 0) {
            return res;
        }
        throw new RuntimeException("删除预收款失败!");
    }

    @Override
    public ListResult<AdvanceReceiptVo> pageBy(AdvanceReceiptVo record) {
        List service_res = dao.queryBy(record);
        int total = dao.countBy(record);
        Pagination page = new Pagination(record.getPage(), total, record.getSize());
        ListResult<AdvanceReceiptVo> res = new ListResult(true, service_res);
        res.setPage(page);
        return res;
    }

    private void accountDesc(Boolean flag, ClienteleAccount ca) {
        if (flag) {
            int res = clienteleAccountService.insertSelective(ca);
            if (res == 0) {
                throw new Error("保存失败!");
            }
        } else { //存在更新
            int res = clienteleAccountService.updateByPrimaryKeySelective(ca);
            if (res == 0) {
                throw new Error("更新失败!");
            }
        }
    }

    private int getMaxInNoOrder(AdvanceReceipt ar) {
        String str = dao.queryCurrentDayMaxNo(ar);
        if (str == null) {
            return 0;
        } else {
            String number = str.split("-")[1];
            return Integer.valueOf(number);
        }
    }

    @Transactional
    @Override
    public Object createAdvancePay(AdvanceReceipt record) {
        record.setType("2"); //
        if (record.getNo() == null) {
            AdvanceReceipt ar = new AdvanceReceipt();
            ar.setNo("YFK");
            record.setNo(Constants.generateServiceNO("YFK", Constants.generateLimitNumberStr(getMaxInNoOrder(ar) + 1, 4)));
        }
        ClienteleAccount ca = clienteleAccountService.selectClientAccountByClientele(record.getClienteleId());
        Boolean flag = false;
        if (ca == null) {
            flag = true;
            ca = new ClienteleAccount();
            ca.setClienteleId(record.getClienteleId());
            ca.setYufuRemain(BigDecimal.valueOf(0.0));
            ca.setYufuTotal(BigDecimal.valueOf(0.0));
        }
        ca.setYufuRemain(record.getTotalDeposit().add(ca.getYufuRemain()));
        ca.setYufuTotal(record.getTotalDeposit().add(ca.getYufuTotal()));
        accountDesc(flag, ca);
        int res = dao.insertSelective(record);
        if (res > 0) {
            return res;
        }
        throw new Error("保存预付款失败!");
    }

    @Transactional
    @Override
    public Object destoryAdvancePay(AdvanceReceipt record) {

        AdvanceReceipt ar = dao.selectByPrimaryKey(record.getId());
        if(ar==null){
            return new RuntimeException("预付款单不存在或已被删除");
        }else if(ar.getTotalVerified().compareTo(BigDecimal.ZERO)==0&&(ar.getLocked()==null||"0".equals(ar.getLocked()))){
            dao.deleteByPrimaryKey(record.getId());
        }
        return new RuntimeException("预付款单不存在或已被删除");
    }

    @Override
    public List<AdvanceReceiptVo> payedToOrder(AdvanceReceipt record) {
        return null;
    }


    @Override
    public AdvanceReceipt selectByPrimaryKey(Integer id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(AdvanceReceipt record) {
        return dao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(AdvanceReceipt record) {
        return dao.updateByPrimaryKey(record);
    }

    @Override
    public int queryCount(AdvanceReceiptVo record) {
        return dao.queryCount(record);
    }

    @Override
    public List<AdvanceReceiptVo> queryByPage(AdvanceReceiptVo record) {
        return dao.queryByPage(record); //
    }

    @Override
    public int queryCurrentDayCount(AdvanceReceipt ar) {
        return getMaxInNoOrder(ar);
    }

    @Override
    public List<AdvanceReceiptVo> queryByClienteleId(AdvanceReceiptVo record) {
        return dao.queryByClienteleId(record);
    }

    @Override
    public Object lockAdvanceBill(AdvanceReceiptVo record) {
        return null;
    }


    @Override
    public int updateAdvanceReceiptInBatch(List<AdvanceReceipt> record) {
        return dao.updateAdvanceReceiptInBatch(record);
    }

    @Override
    public int lockAdvanceReceiptInBatch(List<AdvanceReceipt> record) {
        return dao.lockAdvanceReceiptInBatch(record);
    }

    @Override
    public int releaseLockedAdvanceBill(AdvanceReceipt record) {
        return dao.releaseLockedAdvanceBill(record);
    }

    /**
     *
     * @param id
     * @param totalVerified
     * @return
     */
    @Override
    public int changeNumber(Integer id,BigDecimal totalVerified) {
        AdvanceReceipt ar = new AdvanceReceipt();
        AdvanceReceipt ar1 = dao.selectByPrimaryKey(id);
        ar.setId(id);
        ar.setTotalVerified(ar1.getTotalVerified().add(totalVerified));
        if(ar.getTotalVerified().compareTo(BigDecimal.ZERO)==-1){
            throw new RuntimeException("预"+("0".equals(ar1.getType())?"收":"付")+"款金额错误，不能操作！");
        }
        BigDecimal remain = ar1.getTotalDeposit().subtract(ar.getTotalVerified().abs());
        if(remain.compareTo(BigDecimal.ZERO)==0||remain.compareTo(BigDecimal.ZERO)==1){
            ar.setVerifiedOver("0");
        }else if(remain.compareTo(BigDecimal.ZERO)==-1){
            ar.setVerifiedOver("1");
        }
        return dao.updateByPrimaryKeySelective(ar);
    }
}
